package cn.edu.hhu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/teacher/*")
public class TeacherLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //1获取请求资源的路径
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String uri = request.getRequestURI();
        if (request.getQueryString() != null) {
            uri = uri + "?" + request.getQueryString();
        }
        //2判断是否包含登陆相关资源路径
        if (uri.contains("/login") || uri.contains("/signup")) {
            chain.doFilter(req, resp);
        } else {
            if (request.getSession().getAttribute("teacher") != null) {
                chain.doFilter(req, resp);
            } else {
                request.getSession().setAttribute("fromuri", uri);
                request.setAttribute("msg", "您尚未登陆，请先登录！");
                request.getRequestDispatcher("/WEB-INF/view/teacher/login.jsp").forward(request, resp);
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
